
package biblioteca.dao;

import biblioteca.persistencia.Libro;
import biblioteca.persistencia.Socio;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;




@Repository
public class GenericDaoImplementation <T , PK extends Serializable> implements GenericDao<T, PK> {
	
	
	private static final long serialVersionUID = 1L;
	@PersistenceContext
	EntityManager em;
	
	
	@Override
	public void update(T object) {
	em.merge(object);		
	}

	@Override
	public void remove(T object) {
	em.remove(object);
	}

	@Override
	public void remove(Class<T> typeClass, PK clave) {
	T object = em.find(typeClass, clave);
	em.remove(object);	
		
	}
        
        public int removeAll(Class<T> typeClass) {
        String sql = "DELETE FROM " + typeClass.getSimpleName() + " c";
        return em.createQuery(sql).executeUpdate();
    }

        @Override
	public void insert(T t) {
	em.persist(t);
        System.out.println("insert t= "+t);
	}

	@Override
	public void cerrar() {
	em.close();		
	}

	@Override
	public List<T> getPaginated(Class<T> typeClass, int startPosition,
			int maxResult) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<T> getOrderedPaginated(Class<T> typeClass, int startPosition,
			int maxResult, String order, int dir) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<T> getAll(Class<T> typeClass) {
	final StringBuilder sql = new StringBuilder("select c from ").append(
        typeClass.getSimpleName()).append(" c");
        return (List<T>) em.createQuery(sql.toString()).getResultList();
		
	}

	@Override
	public Integer countAll(Class<T> typeClass) {
	// TODO Auto-generated method stub
	return null;
	}

	@Override
	public T findByPK(Class<T> typeClass, PK id) {
	return em.find(typeClass, id);
	}
        
        @Override
        public T findByDNI(Class<T> typeClass, String criterio) {
        String query = "SELECT FROM Socio c WHERE c.dni='" + criterio + "'";
        Socio c = (Socio) em.createQuery(query).getSingleResult();
        return em.find(typeClass, c.getId());
    }
        
        @Override
        public T  finByIsbn(Class<T> typeClass, String criterio){
            String query = "SELECT FROM Libro c WHERE c.isbn='"+criterio+"'";
            Libro c=(Libro) em.createQuery(query).getResultList();
            return em.find(typeClass, c.getIsbn());
        }

    @Override
	public T find(Class<T> typeClass, PK clave) {
		
		return em.find(typeClass, clave);
	}
	
	
	
	
}
